﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Common.Library
{
    /// <summary>
    /// 专门获取appsettings.json 配置信息帮助类
    /// </summary>
    public class ConfigHelper<T>
    {

        /// <summary>
        /// 数据库配置信息
        /// </summary>
        public Dictionary<string, object> config { get; private set; }

        /// <summary>
        /// 初始化配置
        /// </summary>
        /// <returns></returns>
        public static ConfigHelper<T> InitConfig(string path)
        {
            ConfigHelper<T> configInfo = new ConfigHelper<T>();
            try
            {
                string rootDic = AppDomain.CurrentDomain.BaseDirectory;
                using (StreamReader sr = new StreamReader(Path.Combine(rootDic, path),Encoding.GetEncoding("utf-8")))
                {
                    configInfo.config = JsonConvert.DeserializeObject<Dictionary<string, object>>(sr.ReadToEnd());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return configInfo;
        }


        /// <summary>
        /// 获取节点中的信息
        /// </summary>
        /// <returns></returns>
        public T GetNodeInfo(string key) {

            try
            {
                return  JsonConvert.DeserializeObject<T>(this.config[key].ToString());
            }
            catch 
            {
                return default(T);
            }
        }
    }
}
